﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using TomNet.Web.Mvc;
using TomNet.IMSC.Model.DbModels.Common;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.Account;
using TomNet.Web.Mvc.Security;
using TomNet.Web.Mvc.UI;
using Newtonsoft.Json;
using TomNet.IMSC.Web.Filters;

namespace TomNet.IMSC.Web.Controllers
{
    [Description("管理-后台")]
    public class DefaultController : BaseController
    {
        public IBrokerageRunningsContract BrokerageRunningsContract {get;set; }
        public IMenuContract MenuContract { get; set; }
		public Core.Contracts.Organization.IStaffContract StaffContract { get; set; }
		public Core.Contracts.Organization.IStaffLoginContract StaffLoginContract { get; set; }
		public Core.Contracts.Identity.IRoleContract RoleContract { get; set; }
        public Core.Contracts.Organization.IStaffRolesContract StaffRolesContract { get; set; }
        public Core.Contracts.Organization.IStaffAuthorityContract StaffAuthorityContract { get; set; }
        public Core.Contracts.Identity.IRoleAuthorityContract RoleAuthorityContract { get; set; }
        public Core.Contracts.NewHouse.INewHouseRunningsContract NewHouseRunningsContract { get; set; }
        public Core.Contracts.LowPriceHouse.ILowPriceHouseRunningsContract LowPriceHouseRunningsContract { get; set; }
        public Core.Contracts.Finance.IFinanceRunningsContract FinanceRunningsContract { get; set; }
        public Core.Contracts.Decoration.IDecorationRunningsContract DecorationRunningsContract { get; set; }
        #region ActionResult Index()

        [Description("管理-首页")]
        [GlobalAuthorization]
        public ActionResult Index()
        {

            Dictionary<Menu, int> menu01 = new Dictionary<Menu, int>();
            Dictionary<Menu, List<Menu>> menu02 = new Dictionary<Menu, List<Menu>>();
            Dictionary<Menu, List<Menu>> menu03 = new Dictionary<Menu, List<Menu>>();

			var cookies = Common.CookiesManagement.GetCookies();
			var ticket = Common.CookiesManagement.GetTicket(cookies);
			var model = Common.CookiesManagement.GetLoginModel(ticket);
            UpdateLoginModelAuthorityIds(model);

            ViewBag.LoginModel = TomNet.Utility.Data.JsonHelper.ToJson(model);
            

            bool isCheckAuth = true;//是否根据权限显示菜单

			//一级菜单
			var query = MenuContract.TrackEntities.Where(x =>
				x.ParentID == 0
				&& (!isCheckAuth || x.AuthorityID == 0 || ("," + model.AuthorityIds + ",").IndexOf("," + x.AuthorityID + ",") >= 0)
				).ToList();

            foreach (var item in query)
            {
                int level = 1;//菜单级数

                //二级菜单
                var query2 = MenuContract.TrackEntities.Where(x =>
					x.ParentID == item.Id
					&& (!isCheckAuth || x.AuthorityID == 0 || ("," + model.AuthorityIds + ",").IndexOf("," + x.AuthorityID + ",") >= 0)
					).ToList();

                if (query2.Count()>0)
                {
                    level = 2;//二级

                    foreach (var item2 in query2)
                    {
                        //三级菜单
                        var query3 = MenuContract.TrackEntities.Where(x =>
							x.ParentID == item2.Id
							&& (!isCheckAuth || x.AuthorityID == 0 || ("," + model.AuthorityIds + ",").IndexOf("," + x.AuthorityID + ",") >= 0)
							).ToList();

                        if (query3.Count() > 0)
                        {
                            level = 3;//三级
                            menu03.Add(item2, query3);
                        }
                    }

                    menu02.Add(item, query2);
                }
                                
                menu01.Add(item, level);
            }

            ViewData["Menu01"] = menu01;
            ViewData["Menu02"] = menu02;
            ViewData["Menu03"] = menu03;

            return View(); 
        }

		#endregion

		[Description("管理-登录")]
        public ActionResult Login()
        {
			//LoginAsync("admin", "admin", 1);
			//return RedirectToAction("index");

			FormsAuthentication.SignOut();
			return View();
		}

		#region ActionResult LoginAsync(string name, string pass, int remember)

		[Description("管理-登录")]
        [HttpPost, AjaxOnly]
        public ActionResult LoginAsync(string name, string pass, int remember)
        {
            AjaxResult result = new AjaxResult();
            try
            {
				//pass = Utility.Secutiry.HashHelper.GetMd5(pass);
				var query = (from a in StaffLoginContract.Entities
							 join b1 in StaffContract.Entities on a.StaffID equals b1.Id into tempb
							 from b in tempb.DefaultIfEmpty()
							 where a.LoginName == name && a.LoginPass.Equals(pass, StringComparison.CurrentCultureIgnoreCase) && a.LoginType == 1 && !a.IsDeleted && a.State == 1
							 select new Model.ViewModels.LoginModel
							 {
								 Id = b.Id,
								 Name = b.Name,
								 Sex = b.Sex,
								 SexName = b.Sex == 1 ? "男" : "女",
								 Phone = b.Phone,
								 LoginName = a.LoginName,
								 State = a.State,
								 DepartmentID = b.DepartmentID,
								 AgentId = b.AgentID,
								 RoleId =0,
								 AuthorityIds = "",
                                 UserName=b.Name,
							 }).FirstOrDefault();

				if (query == null)
				{
					result.Type = AjaxResultType.Error;
					result.Content = "账号或密码错误！";
				}
				else
				{
					#region Func

					Func<int, string> GetStateName = delegate (int i) {
						switch (i)
						{
							case 0: return "不可用";
							case 1: return "正常";
							default: return "";
						}
					};
					query.StateName = GetStateName(query.State);

                    #endregion

                    //List<int> al = new List<int>();
                    //var qa = from a in RoleAuthorityContract.Entities
                    //         join
                    //             b in StaffRolesContract.Entities on a.RoleID equals b.RoleID
                    //         where b.StaffID == query.Id
                    //         select a.AuthorityID;
                    //al.AddRange(qa.ToList());
                    //var sa = from a in StaffAuthorityContract.Entities
                    //         where a.StaffID == query.Id
                    //         select a.AuthorityID;
                    //al.AddRange(sa.ToList());

                    //query.AuthorityIds = string.Join(",", al);

                    var data = JsonConvert.SerializeObject(query);
					var ticket = new FormsAuthenticationTicket(
										1,
										name,
										DateTime.Now,
										DateTime.Now.Add(FormsAuthentication.Timeout),
										remember == 1 ? true : false,
										data);
					var cookie = new HttpCookie(
						FormsAuthentication.FormsCookieName,
						FormsAuthentication.Encrypt(ticket));
					cookie.HttpOnly = true;
					Response.Cookies.Add(cookie);

					result.Type = AjaxResultType.Success;
					result.Content = "登录成功！";
				}
			}
            catch (Exception e)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "系统异常！";
            }
            return JsonEx(result);
        }
        [Description("管理-首页")]
        [GlobalAuthorization]
        public ActionResult Main()
        {
            return View(); 
        }
		[Description("管理-登录")]
        [HttpPost, AjaxOnly]
        public ActionResult AlarmAsync()
        {
            AjaxResult result = new AjaxResult();
            try
            {
                var cookies = Common.CookiesManagement.GetCookies();
                var ticket = Common.CookiesManagement.GetTicket(cookies);
                var model = Common.CookiesManagement.GetLoginModel(ticket);
                UpdateLoginModelAuthorityIds(model);
                Model.ViewModels.Alarm m = new Model.ViewModels.Alarm();
                m.NewHouse = NewHouseRunningsContract.Entities.Count(p => p.State == 1 && p.AgentID == model.AgentId);
                m.LowPriceHouse = LowPriceHouseRunningsContract.Entities.Count(p => p.State == 1 && p.AgentID == model.AgentId);
                m.Decoration = DecorationRunningsContract.Entities.Count(p => p.State == 1 && p.AgentID == model.AgentId);
                m.Finance = FinanceRunningsContract.Entities.Count(p => p.State == 1 && p.AgentID == model.AgentId);
                result.Data = m;
                result.Type = AjaxResultType.Success;
                result.Content = "成功！";
            }
            catch (Exception e)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常！";
            }
            return JsonEx(result);
        }

		#endregion
	}
}
